<?php

namespace app\controllers;

use app\models\Hello;
use app\models\User;
use dosamigos\qrcode\QrCode;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class QrcodeController extends Controller
{
    public $enableCsrfValidation = false;

    public function actionRegister()
    {
        if(Yii::$app->request->isPost) {
            $user = new User();
            $user->username = $_POST['username'];
            $user->password = $_POST['password'];
            $user->nick = $_POST['nick'];
            if($user->save()) { //通过save操作保存用户
                return 'success';
            } else {
                var_dump($user->errors);
                return 'fail';
            }
        } else {
            return $this->render('register');
            //return $this->renderPartial('register');
        }
    }

    public function actionLogin()
    {
        $username = $_POST['username'];
        $password = $_POST['password'];

        if($username && $password) {
            $user = User::findOne(['username' => $username]);  //注意findone和find的区别
            //$users = User::find()->where(['username' => $username])->all();//查询所有符合条件的记录
            if(!$user) {
                return '没有该用户';
            }
            if($user->password == $password) { //登录成功
                if(!$user->qrcode) { //如果该用户没有生成过二维码
                    //开始生成二维码
                    $filename =rand(10000,99999).'.png';
                    QrCode::png($user->nick, Yii::$app->basePath.'\web\image\\'.$filename);
                    $user->qrcode =  '/image/'.$filename;
                    $user->update();
                }
                return $this->render('qrcode', [ //展示二维码
                    'qrcode' => $user->qrcode,
                ] );
            } else {
                return '密码错误';
            }
        }

        return $this->render('login', [
        ] );
    }
}
